<?php
namespace app\massage\controller;
use app\ApiRest;

use app\massage\model\Address;
use app\massage\model\Car;
use app\massage\model\CarGame;
use app\massage\model\CarLineUp;
use app\massage\model\CarPrice;
use app\massage\model\CarType;
use app\massage\model\Coach;
use app\massage\model\Comment;
use app\massage\model\CommentLable;
use app\massage\model\Config;

use app\massage\model\Coupon;
use app\massage\model\CouponRecord;
use app\massage\model\Lable;
use app\massage\model\MsgConfig;
use app\massage\model\NoticeList;
use app\massage\model\Order;
use app\massage\model\OrderAddress;
use app\massage\model\OrderGoods;
use app\massage\model\RefundOrder;
use app\massage\model\User;
use think\App;
use think\facade\Db;
use think\Request;


class IndexOrder extends ApiRest
{

    protected $model;

    protected $refund_model;

    protected $order_goods_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Order();

        $this->refund_model = new RefundOrder();

        $this->order_goods_model = new OrderGoods();

//        $this->model->coachBalanceArr($this->_uniacid);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-07-12 00:26
     * @功能说明:天数
     */
    public function dayText(){

        $config_model = new Config();

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        $start_time = strtotime(date('Y-m-d',time()));

       // $start_time = $start_time+$config['max_day']*86400;

        $i=0;

        while ($i<$config['max_day']){

            $str = $start_time+$i*86400;

            $data[$i]['dat_str'] = $str;

            $data[$i]['dat_text'] = date('m-d',$str);

            $data[$i]['week'] = changeWeek(date('w',$str));

            $i++;

        }

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-09 14:41
     * @功能说明:时间段
     */
    public function timeText(){

        $input = $this->_param;

        $config_model = new Config();

        $coach_model  = new Coach();

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        $coach  = $coach_model->dataInfo(['id'=>$input['coach_id']]);

        $end_time   = strtotime($coach['end_time'])- strtotime(date("Y-m-d",time()))+strtotime(date("Y-m-d",$input['day']));

        $start_time = strtotime($coach['start_time'])-strtotime(date("Y-m-d",time()))+strtotime(date("Y-m-d",$input['day']));

        $i = 0;

        $data = [];

        $time = $start_time;

        while ($time<$end_time){

            $time = $start_time+$config['time_unit']*$i*60;
            //时间戳
            $data[$i]['time_str'] = $time;

            $data[$i]['time_text']= date('H:i',$time);

            $where   = [];

            $where[] = ['coach_id','=',$input['coach_id']];

            $where[] = ['start_time','<=',$time];

            $where[] = ['end_time','>=',$time];

            $where[] = ['pay_type','not in',[-1]];

            $order = $this->model->dataInfo($where);

            if(!empty($order)){

                $data[$i]['status'] = 0;

            }else{

                $data[$i]['status'] = 1;

            }

            $data[$i]['status'] = $time<time()?0:$data[$i]['status'];

            $i++;
        }

        return $this->success($data);


    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function orderList(){
        //超时自动取消订单
        $this->model->autoCancelOrder($this->_uniacid,$this->getUserId());

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $dis[] = ['a.is_show','=',1];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['pay_type'])){

            $dis[] = ['a.pay_type','=',$input['pay_type']];

        }

        $data = $this->model->indexDataList($dis,$where);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $can_refund_num = is_array($v['order_goods'])?array_sum(array_column($v['order_goods'],'can_refund_num')):0;
                //是否可以申请退款
//                if(($v['pay_type']==7&&$v['can_tx_date']>time()&&$can_refund_num>0)||(in_array($v['pay_type'],[2,3,4,5,6])&&$can_refund_num>0)){
                if((in_array($v['pay_type'],[2])&&$can_refund_num>0)){

                    $v['can_refund'] = 1;

                }else{

                    $v['can_refund'] = 0;
                }

            }

        }
        //查询待支付订单待条数
        $dis = [

            'pay_type' => 1,

            'user_id'  => $this->getUserId()
        ];

        $data['no_pay_count'] = $this->model->where($dis)->count();

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:58
     * @功能说明:订单详情
     */
    public function orderInfo(){

        $input = $this->_param;


        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

      //  $data['order_end_time'] -= time();

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['pay_time']    = date('Y-m-d H:i:s',$data['pay_time']);

        $data['hx_time']     = date('Y-m-d H:i:s',$data['hx_time']);
        //剩余可申请退款数量
        $can_refund_num = array_sum(array_column($data['order_goods'],'can_refund_num'));
        //是否可以申请退款
        if((in_array($data['pay_type'],[2])&&$can_refund_num>0)){

            $data['can_refund'] = 1;

        }else{

            $data['can_refund'] = 0;
        }

        $data['over_time'] -= time();

        $data['over_time']  = $data['over_time']>0?$data['over_time']:0;

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:29
     * @功能说明:退款订单详情
     *
     */
    public function refundOrderList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','>',-1];

        }

        $data = $this->refund_model->indexDataList($dis,$where);
        //待接单数量
        $data['ing_count'] = $this->refund_model->where(['user_id'=>$this->getUserId(),'status'=>1])->count();

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:50
     * @功能说明:退款订单详情
     */

    public function refundOrderInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->refund_model->dataInfo($dis);

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['refund_time'] = date('Y-m-d H:i:s',$data['refund_time']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 09:43
     * @功能说明:下单页面详情
     */
    public function payOrderInfo(){

        $input = $this->_param;

        $coupon = !empty($input['coupon_id'])?$input['coupon_id']:0;

        $coupon_modle  = new Coupon();

        $coupon_record_model  = new CouponRecord();

        $order_info = $this->model->payOrderInfo($this->getUserId(),$coupon);
        //可用优惠券数量
        $canUseCoupon = $coupon_modle->canUseCoupon($this->getUserId());

        $order_info['canUseCoupon'] = $coupon_record_model->where('id','in',$canUseCoupon)->sum('num');

//        $car_model = new CarPrice();
//
//        $dis = [
//
//            'uniacid' => $this->_uniacid
//        ];
//
//        $order_info['car_config'] = $car_model->dataInfo($dis);

        return $this->success($order_info);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-07-10 00:40
     * @功能说明:可用的优惠券列表
     */
    public function couponList(){

        $input = $this->_param;

        $coupon_model = new Coupon();

        $coupon_record_model = new CouponRecord();

        $coupon_id = $coupon_model->canUseCoupon($this->getUserId());

        $data = $coupon_record_model->where('id','in',$coupon_id)->order('id desc')->paginate(10)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

            }
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 09:53
     * @功能说明:下单
     */
    public function payOrder(){

        $input = $this->_input;

        $coupon_record_model = new CouponRecord();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $coupon_id  = !empty($input['coupon_id'])?$input['coupon_id']:0;

        $order_info = $this->model->payOrderInfo($this->getUserId(),$coupon_id);

        $config_model = new Config();

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        Db::startTrans();

        $member_config_model = new \app\member\model\Config();

        $member_config = $member_config_model->configInfo(['uniacid'=>$this->_uniacid]);

        $order_insert = [

            'uniacid'    => $this->_uniacid,

            'over_time'  => time()+$config['over_time']*60,

            'order_code' => orderCode(),

            'user_id'    => $this->getUserId(),

            'pay_price'  => $order_info['pay_price'],

            'init_price'  => $order_info['init_goods_price'],

            'balance'     => !empty($input['is_balance'])?$order_info['pay_price']:0,

            'discount'    => $order_info['discount'],

            'pay_type'    => 1,

            'mobile'      => $input['mobile'],

            'total_circle'=> $order_info['total_circle'],
            //付费获得的积分
            'get_integral'=> empty($input['is_balance'])?floor($order_info['pay_price']*$member_config['integral_cash']):0,
            //备注
//            'text'        => $input['text'],

//            'can_tx_time' => $config['can_tx_time'],

        ];
        //下单
        $res = $this->model->dataAdd($order_insert);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('下单失败');
        }

        $order_id = $this->model->getLastInsID();
        //使用优惠券
        if(!empty($coupon_id)){

            $coupon_id = $coupon_record_model->couponUse($coupon_id,$order_id);

            $this->model->dataUpdate(['id'=>$order_id],['coupon_id'=>$coupon_id]);

        }
        //添加到子订单
        $res = $this->order_goods_model->orderGoodsAdd($order_info['order_goods'],$order_id,$this->getUserId());

        if(!empty($res['code'])){

            Db::rollback();

            $code = $res['code']==50001?50001:400;

            $this->errorMsg($res['msg'],$code);
        }

        Db::commit();
        //如果是0元
        if($order_insert['pay_price']<=0){

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);
        }
        //余额支付
        if(!empty($input['is_balance'])){

            $user_model = new User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"anmo",['type' => 'Massage' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

        $arr['pay_list']= $jsApiParameters;

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 15:59
     * @功能说明:重新支付
     */
    public function rePayOrder(){

        $input = $this->_input;

        $order_insert = $this->model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }
        //余额支付
        if(!empty($order_insert['balance'])){

            $user_model = new User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"anmo",['type' => 'Massage' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

        $arr['pay_list']= $jsApiParameters;

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-27 13:44
     * @功能说明:核销订单
     */
    public function hxOrder(){

        $input = $this->_input;

        $record = $this->model->dataInfo(['id'=>$input['order_id']]);

        if($record['pay_type']!=3){

            $this->errorMsg('订单状态错误');

        }

        $user_model = new User();

        $user_role = $user_model->where(['id'=>$this->getUserId()])->value('role');

        if($user_role!=1){

            $this->errorMsg('管理员才有核销权限');
        }

        $refund_model = new RefundOrder();
        //判断有无申请中的退款订单
        $refund_order = $refund_model->dataInfo(['order_id'=>$record['id'],'status'=>1]);

        if(!empty($refund_order)){

            $this->errorMsg('该订单正在申请退款，请先处理再核销');

        }

        Db::startTrans();

        $res = $this->model->hxOrder($record,$this->getUserId());

        if($res==0){

            Db::rollback();

            $this->errorMsg('核销失败');

        }

        $game_model = new CarGame();
        //清空当前使用卡
        $game_model->dataUpdate(['now_card_id'=>$input['card_id']],['now_card_id'=>'']);
        //判断类型 专业组还是普通
        $car_type_model = new CarType();

        $type = $car_type_model->getType($record['order_goods'][0]['car_type_id'],$record['user_id']);

        $insert = [

            'uniacid'     => $this->_uniacid,

            'user_id'     => $record['user_id'],

            'record_id'   => $record['id'],

            'card_id'     => $input['card_id'],

            'now_card_id' => $input['card_id'],

            'type'        => 2,

            'major'       => $type,

            'car_type_id' => $record['order_goods'][0]['car_type_id'],


        ];
        //添加比赛记录标 准备开始比赛
        $res = $game_model->dataAdd($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('核销失败');

        }
        //查询是否正在排队
        $line_model = new CarLineUp();

        $dis = [

            'order_id' => $record['id'],

            'type'     => 1
        ];

        $line_model->dataUpdate($dis,['status'=>2]);
        //如果有需要到账的积分
        if(!empty($record['get_integral'])&&$record['have_tx']==0){

            $integral_model = new \app\member\model\Integral();

            $integral_model->integralUserAdd($record['user_id'],$record['get_integral'],$record['uniacid'],2,9,$record['id']);

        }

        Db::commit();

        return $this->success($res);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 16:38
     * @功能说明:取消订单
     */

    public function cancelOrder(){

        $input = $this->_input;

        $order_insert = $this->model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }

       $res = $this->model->cancelOrder($order_insert);

       if(!empty($res['code'])){

           $this->errorMsg($res['msg']);
       }

       return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 11:39
     * @功能说明:申请退款
     */
    public function applyOrder(){

        $input = $this->_input;

        $order = $this->model->dataInfo(['id'=>$input['order_id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if($order['pay_type']<2){

            $this->errorMsg('订单状态错误');

        }

        if(empty($input['list'])){

            $this->errorMsg('请选择商品');

        }
        //申请退款
        $res = $this->refund_model->applyRefund($order,$input);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 15:55
     * @功能说明:取消退款
     */
    public function cancelRefundOrder(){

        $input = $this->_input;

        $order = $this->refund_model->dataInfo(['id'=>$input['id']]);

        if($order['status']!=1){

            $this->errorMsg('订单已经审核');

        }

        Db::startTrans();

        $res = $this->refund_model->dataUpdate(['id'=>$input['id']],['status'=>-1,'cancel_time'=>time()]);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('取消失败');
        }

        if(!empty($order['order_goods'])){

            $order_goods_model = new OrderGoods();

            foreach ($order['order_goods'] as $v){

                if(!empty($v['order_goods_id'])){

                    $num = $v['num'];

                    $res = $order_goods_model->where(['id'=>$v['order_goods_id']])->update(['can_refund_num'=>Db::Raw("can_refund_num+$num")]);

                    if($res!=1){

                        Db::rollback();

                        $this->errorMsg('取消失败');
                    }

                }

            }

        }


        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-07 15:30
     * @功能说明:刷新订单二维码
     */
    public function refreshQr(){

        $input = $this->_input;

//        $qr_insert = [
//
//            'id' => $input['id']
//        ];

        $user_model = new User();
        //获取二维码
        $qr = $user_model->orderQr($input,$this->_uniacid);

        if(!empty($qr)){

            $this->model->dataUpdate(['id'=>$input['id']],['qr'=>$qr]);

        }

        return $this->success($qr);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-13 00:18
     * @功能说明:评价标签
     */
    public function lableList(){

        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 1
        ];

        $lable_model = new Lable();

        $res = $lable_model->where($dis)->order('top desc,id desc')->select()->toArray();

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-07-12 14:01
     * @功能说明:添加评价
     */
    public function addComment(){

        $input = $this->_input;

        $order = $this->model->dataInfo(['id'=>$input['order_id']]);

        if($order['is_comment']==1){

            $this->errorMsg('你已经评价过了');
        }

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'order_id'=> $input['order_id'],

            'star'    => $input['star'],

            'text'    => $input['text'],

            'coach_id'=> $order['coach_id'],

        ];

        Db::startTrans();

        $comment_model = new Comment();

        $coach_model   = new Coach();

        $comment_lable_model   = new CommentLable();

        $lable_model = new Lable();

        $res = $comment_model->dataAdd($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('评价失败');
        }

        $comment_id = $comment_model->getLastInsID();

        if(!empty($input['lable'])){

            foreach ($input['lable'] as $value){

                $title = $lable_model->where(['id'=>$value])->value('title');

                $insert = [

                    'uniacid'    => $this->_uniacid,

                    'comment_id' => $comment_id,

                    'lable_id'   => $value,

                    'lable_title'=> $title,

                ];

                $comment_lable_model->dataAdd($insert);
            }

        }

        $all_count = $comment_model->where(['coach_id'=>$order['coach_id']])->count();

        $all_star = $comment_model->where(['coach_id'=>$order['coach_id']])->sum('star');

        $now_star = round($all_star/$all_count,1);

        $now_star = $now_star>5?5:$now_star;

        $coach_model->dataUpdate(['id'=>$order['coach_id']],['star'=>$now_star]);

        $res = $this->model->dataUpdate(['id'=>$order['id']],['is_comment'=>1]);

        if($res==0){

            Db::rollback();

            $this->errorMsg('评价失败');
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-16 18:35
     * @功能说明:删除订单
     */
    public function delOrder(){

        $input = $this->_input;

        $order = $this->model->dataInfo(['id'=>$input['id']]);

        if($order['pay_type']!=-1){

            $this->errorMsg('只有取消的订单才能删除');
        }

        $res = $this->model->dataUpdate(['id'=>$input['id']],['is_show'=>0]);

        return $this->success($res);

    }






}
